package com.cnpinxi.controller.base;

import com.cnpinxi.domain.ExpressInfo;
import com.cnpinxi.domain.OrderItem;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.result.ResultObj;
import com.cnpinxi.service.ExpressInfoService;
import com.cnpinxi.service.OrderItemService;
import com.cnpinxi.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2017-12-1.
 */
@RequestMapping("/logistics")
@Controller
public class LogisticsController {
@Autowired
ExpressInfoService expressInfoService;
   @Autowired
   OrderService orderService;
    @Autowired
    OrderItemService orderItemService;
    @RequestMapping(value = "/checkLogistics")
    @ResponseBody
    public String checkLogistics(Long orderItemId) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);

        try {
            String logistics=expressInfoService.checkLogistics(orderItemId);
            resultObj.setData(logistics);
        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultObj.toJson();
    }
    @RequestMapping(value = "/addExpressInfo")
    @ResponseBody
    public String addExpressInfo(ExpressInfo expressInfo) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);

        try {
             expressInfoService.modifyExpressInfo(expressInfo);

            orderService.modifyOrderStatus(expressInfo.getOrderId(), OrderService.DISPATCHED);
            Map<String,String> map=new HashMap<>();
            map.put("orderId",String.valueOf(expressInfo.getOrderId()));
            List<OrderItem> orderItemList=orderItemService.selectOrderItemList(map);
            for (OrderItem orderItem:orderItemList
                 ) {
                orderItem.setStatus(OrderService.DISPATCHED);
                orderItemService.modifyOrderItem(orderItem);
            }

        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultObj.toJson();
    }
}
